class ListNode {
    int val;
    //套定义ListNode类型
    ListNode next;
    ListNode(int x) { val = x; }
}

public class ReverseLinkedList {
    public static void main(String[] args) {
        // 创建一个测试链表 1 -> 2 -> 6 -> 3 -> 4 -> 5 -> 6
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(6);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(4);
        head.next.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next.next = new ListNode(6);

        //调用内部类中的方法
        ListNode result = Solution.reverseList(head);

        // 打印结果链表
        while (result != null) {
            System.out.print(result.val + " ");
            result = result.next;
        }
    }

    static class Solution {
        public static ListNode reverseList(ListNode head) {
            if (head == null) {
                return null;
            }
            //工具，用于遍历链表
            ListNode i = head;
            ListNode back = null;

            while (i != null) {
                //工具，用于使i维持链表正方向
                ListNode tool = i.next;
                //将i的下一个值锁定为空,之后每一次锁定都为head逆序节点值
                i.next = back;
                //这就是下一次锁定值
                back = i;
                //将head的顺序下一值赋给i
                i = tool;
            }

            return back;
        }
    }
}
